import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_class2/3681/accountRelated/account_controller.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:toast/toast.dart';

import 'news_json_resp.dart';
import 'news_listbuilder.dart';
// import 'news_channel.dart';


/**
 * 头条新闻
 */
class NewList extends StatefulWidget{
  @override
  _NewListState createState() => _NewListState();
}

class _NewListState extends State<NewList> with SingleTickerProviderStateMixin{
  
  List<ChannelList> _channelList;
  NewsData _newsData;
  String defaultUrl="https://v.juhe.cn/toutiao/index?";// 使用http会导致访问不安全而请求失败
  String key="key=b315c04b6387c68b4199f8f9b219e83b";// 访问新闻接口的唯一key
  String type="type=";// 访问新闻接口时指定新闻类型（头条、军事、科技...）
  String page="page=";// 访问新闻接口时指定页数（接口可提供30页，默认为1）
  String url;// 将上述信息合并为一个完整的接口地址
  ChannelList currentChannel;

  bool isLoading= false;
  List<Widget>  listItems;
  var dataItemDatabaseHelper = DataItemDatabaseHelper();

  @override
  Widget build(BuildContext context) {

    addChannelList();

    final popupMenuEntry = <PopupMenuEntry<String>>[
      MyPopupMenuItem(Icons.local_fire_department, Colors.redAccent, '0', '头条'),
      MyPopupMenuItem(Icons.architecture, Colors.grey, '1', '社会'),
      MyPopupMenuItem(Icons.where_to_vote, Colors.grey, '2', '国内'),
      MyPopupMenuItem(Icons.where_to_vote_outlined, Colors.grey, '3', '国际'),
      MyPopupMenuItem(Icons.wine_bar, Colors.grey, '4', '娱乐'),
      MyPopupMenuItem(Icons.directions_run, Colors.grey, '5', '体育'),
      MyPopupMenuItem(Icons.assistant_photo, Colors.grey, '6', '军事'),
      MyPopupMenuItem(Icons.settings, Colors.grey, '7', '科技'),
      MyPopupMenuItem(Icons.account_balance_wallet, Colors.grey, '8', '财经'),
      MyPopupMenuItem(Icons.wc, Colors.grey, '9', '时尚'),
    ];

    final channelButton = FloatingActionButton(
      tooltip: "刷新",
      child: PopupMenuButton<String>(
        icon: Icon(Icons.list),
        tooltip: "切换频道",
        offset: Offset(0,-490),//调节弹出菜单的相对位置
        onSelected: (value){
          currentChannel = _channelList[int.parse(value)];
          refresh();
        },
        itemBuilder: (context) {
          return popupMenuEntry;
        },
        enableFeedback: true,
      ),
    );

    return Scaffold(
      body: Center(
        child: listItems !=null ?
        RefreshIndicator(
            onRefresh: ()async{
              setState(() {
                refresh();
              });
            },
            displacement: 50,
            color:Colors.white,
            backgroundColor: Colors.blue,
            child: AnimationLimiter(
                child: ListView.builder(
                    itemCount: listItems.length,
                    itemBuilder: (context ,index){
                      return AnimationConfiguration.staggeredList(
                          position: index,
                          duration: const Duration(milliseconds: 360),
                          child: SlideAnimation( // 滑动动画
                            child: FadeInAnimation( // 渐变动画
                              child: listItems[index],
                            ),
                          )
                      );
                    }
                )
            ),
        )
            : Text("请点击右下角按钮以选择频道"),

      ),
      floatingActionButton: channelButton,
    );
  }

  addChannelList(){
    _channelList=new List();
    _channelList.add(new ChannelList("top", "头条"));
    _channelList.add(new ChannelList("shehui", "社会"));
    _channelList.add(new ChannelList("guonei", "国内"));
    _channelList.add(new ChannelList("guoji", "国际"));
    _channelList.add(new ChannelList("yule", "娱乐"));
    _channelList.add(new ChannelList("tiyu", "体育"));
    _channelList.add(new ChannelList("junshi", "军事"));
    _channelList.add(new ChannelList("keji", "科技"));
    _channelList.add(new ChannelList("caijing", "财经"));
    _channelList.add(new ChannelList("shishang", "时尚"));
    currentChannel=_channelList[0];
  }

  //获取新闻、切换新闻类型后刷新数据
  refresh() async{
    url="$defaultUrl$type${currentChannel.type}&$key";
    debugPrint("url:$url");
    if(!isLoading){
      isLoading = true;
      try{
        HttpClient httpClient = new HttpClient();// ---接口访问开始
        HttpClientRequest request = await httpClient.getUrl(Uri.parse(url));
        HttpClientResponse response = await request.close();
        String responseContent = await response.transform(utf8.decoder).join();
        _newsData = NewsData.fromJson(json.decode(responseContent));
        listItems = ListBuilder.genWidgetsFromJson(_newsData, context);
        int listItemsSize=listItems.length;
        debugPrint("NewList listItemsSize:$listItemsSize");
        setState(() {}); // 刷新界面（主要是刷新listItems的数据）
        Toast.show('刷新成功', context);
        httpClient.close();// ---接口访问结束
        List<DataItem> list_dataItems = _newsData.result.data.dataItems;// 进行新闻的缓存
        successNewsCache(dataItemDatabaseHelper, list_dataItems);
      } catch (e){
        debugPrint("请求失败：$e");
        Toast.show("从网络获取新闻数据失败，加载本地数据", context);

        //从本地获取已缓存的新闻列表
        var list_dataItems = await dataItemDatabaseHelper.getAllDataItems();
        print("NewList 本地新闻列表：");
        for(int i=0; i<list_dataItems.length; i++){
          print(list_dataItems[i].toString());
        }
        Data da = Data.fromJson(list_dataItems);
        Result re = new Result('error', da);
        _newsData = new NewsData('error', re, 0);
        listItems = ListBuilder.genWidgetsFromJson(_newsData, context);

      }finally {
        setState(() {
          isLoading = false;
        });
      }
    }else{
      debugPrint("正在刷新");
    }
  }

  //异步存储新闻缓存信息
  Future<void> successNewsCache(DataItemDatabaseHelper db, List<DataItem> dataItems ) async {
    print("NewList 新闻缓存:");
    await db.clearDataItem();//先清空数据库，再进行缓存
    for(int i=0; i<dataItems.length; i++){
      await db.saveDataItem(i.toString(), dataItems[i]);
    }
    // await db.saveDataItem(new DataItem(uniquekey, title, date, category, author_name, url, thumbnail_pic_s, thumbnail_pic_s02, thumbnail_pic_s03));
    print("NewList 新闻缓存结束");
  }
}

// 新闻频道的名称和类型
class ChannelList{
  String name;
  String type;
  ChannelList(this.type,this.name);
}

//自定义一个弹出菜单项
Widget MyPopupMenuItem(IconData icon,Color iconColor,String value,String text) {
  return PopupMenuItem<String>(
    value: value,
    child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(icon, color: iconColor, ),
        Text("   " + text),
      ],
    ),
  );
}